package pers.brozen.anka.utils;

import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.util.Random;

public class MD5Utils {
	private static final String[] hexDigits = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

	public MD5Utils() {
	}

	private static String toHex(byte[] bytes) {
		StringBuilder hex = new StringBuilder();
		byte[] var2 = bytes;
		int var3 = bytes.length;

		for(int var4 = 0; var4 < var3; ++var4) {
			byte b = var2[var4];
			hex.append(toHex(b));
		}

		return hex.toString();
	}

	private static String toHex(byte b) {
		int n = b;
		if (b < 0) {
			n = b + 256;
		}

		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	public static String md5AndHex(String origin, String charset) {
		charset = charset == null ? "UTF-8" : charset;

		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			String resultString;
			if (StringUtils.isBlank(charset)) {
				resultString = toHex(md.digest(origin.getBytes()));
			} else {
				resultString = toHex(md.digest(origin.getBytes(charset)));
			}

			return resultString;
		} catch (Exception var4) {
			throw new IllegalStateException("加密失败！", var4);
		}
	}

	public static String md5WithSalt(String input) {
		Random random = new Random();
		StringBuilder saltBuilder = new StringBuilder(16);
		saltBuilder.append(random.nextInt(99999999)).append(random.nextInt(99999999));
		int len = saltBuilder.length();
		if (len < 16) {
			for(int i = 0; i < 16 - len; ++i) {
				saltBuilder.append("0");
			}
		}

		String salt = saltBuilder.toString();
		input = md5AndHex(input + salt, (String)null);
		char[] cs = new char[48];

		for(int i = 0; i < 48; i += 3) {
			cs[i] = input.charAt(i / 3 * 2);
			char c = salt.charAt(i / 3);
			cs[i + 1] = c;
			cs[i + 2] = input.charAt(i / 3 * 2 + 1);
		}

		return String.valueOf(cs);
	}

	public static boolean verify(String input, String encrypted) {
		char[] cs1 = new char[32];
		char[] cs2 = new char[16];

		for(int i = 0; i < 48; i += 3) {
			cs1[i / 3 * 2] = encrypted.charAt(i);
			cs1[i / 3 * 2 + 1] = encrypted.charAt(i + 2);
			cs2[i / 3] = encrypted.charAt(i + 1);
		}

		String Salt = new String(cs2);
		return md5AndHex(input + Salt, (String)null).equals(String.valueOf(cs1));
	}

	public static void main(String[] args) {
		// 原密码
		String plaintext = "$u@pBGBJ";

		// 获取加盐后的MD5值
		String ciphertext = md5WithSalt(plaintext);
		System.out.println("加盐后MD5：" + ciphertext);
		System.out.println("是否是同一字符串:" + verify(plaintext, ciphertext));

		String test = "b9cb58b12e1447357b431b1b21cd9750d20888582695ea25";
		System.out.println("是否是同一字符串:" + verify(plaintext, test));
	}

}